<template>
  <div>
    <a-form-item label="选择短信发送服务商">
      <a-radio-group v-model:value="vdata.configData.smsProvideKey">
        <a-radio value="jeepaydx"><fire-filled style="color: rgb(200, 20, 20);" /> 计全短信 </a-radio>
        <a-radio value="aliyundy">阿里云短信服务</a-radio>
        <a-radio value="mocktest">模拟测试</a-radio>
      </a-radio-group>
    </a-form-item>

    <!-- 计全短信配置项 -->
    <a-form v-if="vdata.configData.smsProvideKey == 'jeepaydx' && vdata.configData.jeepaydx" ref="smsInfoFormModelByJeepaydx" :rules="rules.jeepaydx" :model="vdata.configData.jeepaydx" layout="vertical">
      <div style=" background: #ddf6fc; height: 40px; line-height: 40px; width: 95%; border-radius: 5px;">
        <span style="margin-left: 20px;">开通计全短信通道请联系官方：18611727422，
          <a href=" https://www.jeequan.com/goods/list_1008_1010.html " target="_blank">点击链接</a> 可进行短信的开通和购买。
        </span>
      </div>
      <a-divider orientation="left">计全短信-账号配置</a-divider>
      <a-row>
        <a-col :span="6" :offset="2">
          <a-form-item label="用户名" name="userName">
            <a-input v-model:value="vdata.configData.jeepaydx.userName" type="text" placeholder="请填写用户名" />
          </a-form-item>
        </a-col>
        <a-col :span="6" :offset="2">
          <a-form-item label="密码" name="accountPwd">
            <a-input v-model:value="vdata.configData.jeepaydx.accountPwd" type="text" :placeholder="getConfigValDesen('jeepaydx', 'accountPwd')" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="6" :offset="2">
          <a-form-item label="短信签名" name="signName">
            <a-input v-model:value="vdata.configData.jeepaydx.signName" type="text" placeholder="请填写 [短信签名]" />
          </a-form-item>
        </a-col>
        <a-col :span="6" :offset="2">
          <a-form-item label="短信余额（条）">
            <span v-if="vdata.smsBalance || vdata.smsBalance == 0">
              <span style="color: blue;"><b>{{ vdata.smsBalance }}</b></span> 条
            </span>
            <span v-else>未知</span>

            <span style="margin-left: 20px;">
              <a href=" https://www.jeequan.com/goods/list_1008_1010.html" target="_blank">  [充值]</a> 
            </span>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    
    <!-- 阿里云短信配置项 -->
    <a-form v-if="vdata.configData.smsProvideKey == 'aliyundy' && vdata.configData.aliyundy" ref="smsInfoFormModelByAliyundy" :rules="rules.aliyundy" :model="vdata.configData.aliyundy" layout="vertical">
      <a-divider orientation="left">阿里云短信服务-账号配置</a-divider>
      <a-row>
        <a-col :span="6" :offset="2">
          <a-form-item label="accessKeyId" name="accessKeyId">
            <a-input v-model:value="vdata.configData.aliyundy.accessKeyId" type="text" placeholder="请填写" />
          </a-form-item>
        </a-col>
        <a-col :span="6" :offset="2">
          <a-form-item label="accessKeySecret" name="accessKeySecret">
            <a-input v-model:value="vdata.configData.aliyundy.accessKeySecret" type="text" :placeholder="getConfigValDesen('aliyundy', 'accessKeySecret')" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="6" :offset="2">
          <a-form-item label="短信签名" name="signName">
            <a-input v-model:value="vdata.configData.aliyundy.signName" type="text" placeholder="请填写 [短信签名]" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-divider orientation="left">模板ID配置</a-divider>
      <a-row>
        <a-col :span="6" :offset="2">
          <a-form-item label="" name="registerMchTemplateId">
            <div class="flex">
              <span style="color:red">*</span>  <span>【商户注册】短信模板ID</span>
              <a-popover title="提示模板">
                <template #content>
                  <p>*tip： 您在阿里云的短信模板请使用 ${code}作为参数。</p>
                  <p>示例： 您正在进行注册， 验证码为：${code}，该验证码 1 分钟内有效，请勿泄漏于他人。</p>
                </template>
                <i class="bi bi-info-circle" />
              </a-popover>
            </div>
            <a-input v-model:value="vdata.configData.aliyundy.registerMchTemplateId" type="text" placeholder="请填写 [商户注册短信模板ID]" />
          </a-form-item>
        </a-col>
        <a-col :span="6" :offset="2">
          <a-form-item label="" name="forgetPwdTemplateId">
            <div class="flex">
              <span style="color:red">*</span>   <span>【忘记密码】短信模板ID</span>
              <a-popover title="提示模板">
                <template #content>
                  <p>*tip： 您在阿里云的短信模板请使用 ${code}作为参数。</p>
                  <p>示例： 您正在找回密码操作， 验证码为：${code}，该验证码 1 分钟内有效，请勿泄漏于他人。</p>
                </template>
                <i class="bi bi-info-circle" />
              </a-popover>
            </div>
            <a-input v-model:value="vdata.configData.aliyundy.forgetPwdTemplateId" type="text" placeholder="请填写 [忘记密码短信模板ID]" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="6" :offset="2">
          <a-form-item label="" name="loginMchTemplateId">
            <div class="flex">
              <span style="color:red">*</span> <span>【短信登录】短信模板ID</span>
              <a-popover title="提示模板">
                <template #content>
                  <p>*tip： 您在阿里云的短信模板请使用 ${code}作为参数。</p>
                  <p>示例： 您正在进行登录， 验证码为：${code}，该验证码 1 分钟内有效，请勿泄漏于他人。</p>
                </template>
                <i class="bi bi-info-circle" />
              </a-popover>
            </div>
            <a-input v-model:value="vdata.configData.aliyundy.loginMchTemplateId" type="text" placeholder="请填写 [短信登录短信模板ID]" />
          </a-form-item>
        </a-col>
        <a-col :span="6" :offset="2">
          <a-form-item label="" name="accountOpenTemplateId">
            <div class="flex">
              <span>【账号开通】短信模板ID</span>
              <a-popover title="提示模板">
                <template #content>
                  <p>*tip： 您在阿里云的短信模板请使用 ${loginName} 和 ${loginPwd}作为参数。</p>
                  <p>示例： 账号：${loginName} ，密码：${loginPwd} ，您的账户已开通成功，请勿泄漏于他人。</p>
                </template>
                <i class="bi bi-info-circle" />
              </a-popover>
            </div>
            <a-input v-model:value="vdata.configData.aliyundy.accountOpenTemplateId" type="text" placeholder="请填写 [账号开通短信模板ID]" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row v-if="$hasMemberEnt()">
        <a-col :span="6" :offset="2">
          <a-form-item label="" name="mbrTelBindTemplateId">
            <div class="flex">
              <span style="color:red">*</span> <span>【会员绑定】短信模板ID</span>
              <a-popover title="提示模板">
                <template #content>
                  <p>*tip： 您在阿里云的短信模板请使用 ${code}作为参数。</p>
                  <p>示例： 您正在进行会员绑定操作， 验证码为：${code}，该验证码 1 分钟内有效，请勿泄漏于他人。</p>
                </template>
                <i class="bi bi-info-circle" />
              </a-popover>
            </div>
            <a-input v-model:value="vdata.configData.aliyundy.mbrTelBindTemplateId" type="text" placeholder="请填写 [会员绑定短信模板ID]" />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>

    <!-- 模拟测试 -->
    <a-form v-if="vdata.configData.smsProvideKey == 'mocktest' && vdata.configData.mocktest" ref="smsInfoFormModelByMocktest" :rules="rules.mocktest" :model="vdata.configData.mocktest" layout="vertical">
      <a-divider orientation="left">模拟测试-账号配置</a-divider>
      <a-row>
        <a-col :span="12" :offset="2">
          <a-form-item label="模拟验证码(六位数字)" name="mockCode">
            <a-input v-model:value="vdata.configData.mocktest.mockCode" type="text" placeholder="请填写模拟验证码" />
          </a-form-item>
          <p style="color: red;">特别注意： 模拟测试不会下发短信，所有验证码均为设置项， 仅用做测试，生产环境不可配置！ </p>
        </a-col>
      </a-row>
    </a-form>

    <a-form-item class="bottom-btn" style="margin-top: 10px">
      <a-button v-if="$access('ENT_SYS_CONFIG_EDIT')" :disabled="!vdata.isEdit" type="primary" :loading="vdata.btnLoading" @click="confirmSmsConfig"><check-circle-outlined />确认更新</a-button>
    </a-form-item>
  </div>
</template>

<script setup lang="ts">
import { API_URL_SYS_CONFIG, req, $getSmsBalance } from '@/api/manage'
import { ref, reactive, getCurrentInstance } from 'vue'
const { $infoBox, $access, $hasMemberEnt } = getCurrentInstance()!.appContext.config.globalProperties

const smsInfoFormModelByJeepaydx = ref()
const smsInfoFormModelByAliyundy = ref()
const smsInfoFormModelByMocktest = ref()

const rules = {

    jeepaydx:{
        userName: [{ required: true, message: '请填写用户名', trigger: 'blur' }],
        accountPwd: [{ required: true, message: '请填写密码', trigger: 'blur', validator: ruleProcessByDesen }],
        signName: [{ required: true, message: '请填写签名', trigger: 'blur' }],
    },

    aliyundy: {
        accessKeyId: [{ required: true, message: '请填写accessKeyId', trigger: 'blur' }],
        accessKeySecret: [{ required: true, message: '请填写accessKeySecret', trigger: 'blur', validator: ruleProcessByDesen }],
        signName: [{ required: true, message: '请填写signName', trigger: 'blur' }],
        forgetPwdTemplateId: [{ required: true, message: '请填写忘记密码短信模板ID', trigger: 'blur' }],
        registerMchTemplateId: [{ required: true, message: '请填写商户注册短信模板ID', trigger: 'blur' }],
        loginMchTemplateId: [{ required: true, message: '请填写短信登录短信模板ID', trigger: 'blur' }],
        accountOpenTemplateId: [{ required: false, message: '请填写短信登录短信模板ID', trigger: 'blur' }]
  },
  mocktest:{
        mockCode: [{ required: true, message: '模拟发送的验证码', trigger: 'blur' }],
    },
}

const vdata : any = reactive ({
  isEdit:$access('ENT_SYS_CONFIG_EDIT'),
  btnLoading: false,
  smsConfigRules: {}, // form rules 

  // 配置数据， 转换为： K（configKey） - v (configVal JSON) 格式
  // 例如： 
  // { smsProvideKey: '', jeepaydx: {appId: ''}  jeepaydxDesen: {}  }
  configData: { smsProvideKey : 'jeepaydx' },
  smsBalance: null // 短信余额
  
})


function getFormData(){

    if(vdata.configData.smsProvideKey == 'jeepaydx'){
        return smsInfoFormModelByJeepaydx.value.validate().then(valid => {
            return {'jeepaydxSmsConfigValue': JSON.stringify(vdata.configData.jeepaydx)}
        })
    }

    if(vdata.configData.smsProvideKey == 'aliyundy'){
        return smsInfoFormModelByAliyundy.value.validate().then(valid => {
            return {'aliyundySmsConfigValue': JSON.stringify(vdata.configData.aliyundy)}
        })
    }

    if(vdata.configData.smsProvideKey == 'mocktest'){
        return smsInfoFormModelByMocktest.value.validate().then(valid => {
            return {'mocktestSmsConfigValue': JSON.stringify(vdata.configData.mocktest)}
        })
    }

}


// 短信配置确认更新
function confirmSmsConfig (e) {

    getFormData().then( reqData => {
        $infoBox.confirmPrimary('确认更新短信配置吗？', '', () => {

            vdata.btnLoading = true // 打开按钮上的 loading

            reqData.smsProvideKey = vdata.configData.smsProvideKey

            // 请求更新 
            req.updateById(API_URL_SYS_CONFIG, 'smsConfig', reqData).then(res => {

                $infoBox.message.success('修改成功')

            }).finally(() => {
                vdata.btnLoading = false
            })
            
        })
    })

}

// 通用处理脱敏数据逻辑
function ruleProcessByDesen(rule, value, callback){

    let result = (vdata.configData[ vdata.configData.smsProvideKey +  'Desen'] || {} )[rule.field]

    if (!result && !value) {
        return Promise.reject(new Error(rule.message))
    }
    return Promise.resolve()
}


// 获取脱敏数据 
function getConfigValDesen(smsProvideKey, configKey){

    let result = (vdata.configData[smsProvideKey + 'Desen'] || {} )[configKey]

    return (result || '请输入')

}

// jeepaydxSmsConfigValue  == jeepaydx
function getOriginCofigKey(configKey){

    if(configKey.indexOf('SmsConfigValue') >= 0){
        return configKey.substring(0, configKey.indexOf('SmsConfigValue'))
    }

    return configKey
}

// 查询短信余额
function getSmsBalance(bizQueryType){
  $getSmsBalance(bizQueryType).then(res => {
    vdata.smsBalance = res
  }).catch ((error) =>{console.log(error)} )
}

// 查询结果是异步的， 需要一个函数传递初始化数据 
function pageRender(configDataRes){

    // 配置的原始数据 
    vdata.configData = { smsProvideKey : 'jeepaydx' }

    configDataRes.forEach(item => {

        if(item.configKey == 'smsProvideKey'){ // 无需转换 

            vdata.configData.smsProvideKey = item.configVal 

            // 查询短信余额信息
            if (vdata.configData.smsProvideKey == 'jeepaydx') {
              getSmsBalance(null)
            }

        }else{

            let configKey = getOriginCofigKey(item.configKey)

            vdata.configData[configKey] = JSON.parse(item.configVal) // 转换为 json格式 

            // 包含脱敏数据
            if(item.configValDesen){
                vdata.configData[configKey + 'Desen'] = JSON.parse(item.configValDesen)
            }
        }
    })

}

defineExpose( { pageRender } )
</script>
<style lang="less" scoped>
.flex {
  display:flex;
  margin-bottom: 8px;
  i {
    margin-left: 5px;
  }
}
  .bottom-btn{
    /deep/ div{
      display: flex;
      justify-content: center;
    }
  }

</style>